/**
 * @author chuzhixin 1204505056@qq.com （不想保留author可删除）
 * @description 路由拦截状态管理，目前两种模式：all模式与intelligence模式，其中partialRoutes是菜单暂未使用
 */
import { asyncRoutes, constantRoutes } from '@/router'
import { getRouterList } from '@/api/router'
import { convertRouter, filterAsyncRoutes } from '@/utils/handleRoutes'
import { channelList } from '@/api/news'
import Layout from '@/layouts'

const state = () => ({
  routes: [],
  partialRoutes: [],
})
const getters = {
  routes: (state) => state.routes,
  partialRoutes: (state) => state.partialRoutes,
}
const mutations = {
  setRoutes(state, routes) {
    state.routes = constantRoutes.concat(routes)
  },
  setAllRoutes(state, routes) {
    state.routes = constantRoutes.concat(routes)
  },
  setPartialRoutes(state, routes) {
    state.partialRoutes = constantRoutes.concat(routes)
  },
}
const actions = {
  async setRoutes({ commit }, permissions) {
    // 自定义动态路由
    let channelRoutes = []
    // let { data } = await channelList({pageNum:1,pageSize:100})
    // let rows = data.records
    let rows = []
    // console.log('setRoutes', data, rows)
    if(rows.length>0) {
      let channelRoute =
        {
          path: "/list",
          component: Layout,
          redirect: "noRedirect",
          name: 'Channels',
          alwaysShow: true,
          meta: { title: '新闻内容', icon: 'box-open' },
          children: []
        }
      rows.forEach(row => {
        let rt =
          {
            path: ''+row.id,
            props: { channelId:row.id },
            name: row.channelAlias+row.id,
            component: () => import("@/views/news/list/index"),
            meta: {
              title: row.channelName,
              icon: "marker",
              permissions: ["admin"],
            },
          }
        channelRoute.children.push(rt)
      })
      channelRoutes.push(channelRoute)
    }

    //开源版只过滤动态路由permissions，admin不再默认拥有全部权限
    const finallyAsyncRoutes = await filterAsyncRoutes(
      [...asyncRoutes, ...channelRoutes],
      permissions
    )
    console.log('finallyAsyncRoutes', permissions,finallyAsyncRoutes)
    commit('setRoutes', finallyAsyncRoutes)
    return finallyAsyncRoutes
  },
  async setAllRoutes({ commit }) {
    let { data } = await getRouterList()
    data.push({ path: '*', redirect: '/404', hidden: true })
    let accessRoutes = convertRouter(data)
    commit('setAllRoutes', accessRoutes)
    return accessRoutes
  },
  setPartialRoutes({ commit }, accessRoutes) {
    commit('setPartialRoutes', accessRoutes)
    return accessRoutes
  },
}
export default { state, getters, mutations, actions }
